import org.jsoar.kernel.Agent;
import org.jsoar.kernel.SoarException;
import org.jsoar.kernel.events.OutputEvent;
import org.jsoar.kernel.io.InputBuilder;
import org.jsoar.kernel.io.InputOutput;
import org.jsoar.kernel.memory.Wme;
import org.jsoar.kernel.symbols.SymbolFactory;
import org.jsoar.util.commands.SoarCommandInterpreter;
import org.jsoar.util.commands.SoarCommands;
import org.jsoar.util.events.SoarEvent;

import java.io.OutputStreamWriter;
import java.util.Iterator;

/**
 * @author Zhang Ziyi
 */
public class HelloWorld {
    public static void main(String[] args) {
        // 创建 JSoar 智能体
        Agent agent = new Agent();
        String msg = "";

        try {
            // 获取智能体的解释器
            SoarCommandInterpreter interpreter = agent.getInterpreter();

            // 加载 Soar 文件
            SoarCommands.source(interpreter, "Z:\\code2\\soar\\hello-world\\hello-world.soar");
            System.out.println("Soar file loaded successfully.");

            // 向 input-link 添加属性
            InputOutput io = agent.getInputOutput();
            SymbolFactory syms = io.getSymbols();
            io.addInputWme(io.getInputLink(), syms.createString("message"), syms.createString("Hello JSoar!"));

            // 将运行结果输出到控制台
            agent.getPrinter().pushWriter(new OutputStreamWriter(System.out));

            // 运行智能体一段时间
            agent.runForever();

            // 获取输出
            Iterator<Wme> wmes = io.getOutputLink().getWmes();
            while (wmes.hasNext()) {
                Wme wme = wmes.next();
                if (wme.getAttribute().toString().equals("message")) {
                    msg = wme.getValue().toString();
                }
            }
        } catch (SoarException e) {
            e.printStackTrace();
            System.err.println("Failed to load Soar file: " + e.getMessage());
        } finally {
            // 清理并关闭智能体
            agent.dispose();
        }

        System.out.println("从程序中获取的输出为：" + msg);
    }
}
